<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="部门id：">
                            <el-input v-model="transferVal" placeholder="请输入部门id" />
                        </el-form-item> -->
						<!-- <el-form-item label="变更类型：">
                            <el-select v-model="transferVal1" class="m-2" placeholder="请选择变更类型">
                                <el-option v-for="item in options1" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="变更状态：">
                            <el-select v-model="transferVal2" class="m-2" placeholder="请选择变更状态">
                                <el-option v-for="item in options2" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('ChangeAccount1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('ChangeAccount7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />

										<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" label="变更类型">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="changeType" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.changeType }}
												</template>
											</el-table-column>
										</el-table-column>

										<el-table-column min-width="120" :show-overflow-tooltip="true" label="变更状态" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="status" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.status }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="部门名称" align="center">
											<template #default="scope">
												<span v-if="scope.row.departmentName">{{ scope.row.departmentName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="区域名称" align="center">
											<template #default="scope">
												<span v-if="scope.row.regionsName">{{ scope.row.regionsName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>

										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="updatedTime" label="更新时间" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="updatedUserName" label="更新人" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="180" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" align="center" fixed="right">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button @click="detailHandle(scope.row)" class="icon-e" icon="ele-View" size="small" text type="success"> 详情 </el-button>
														<el-button v-if="$hasPer('ChangeAccount2:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>
														<el-button v-if="$hasPer('ChangeAccount3:file')" size="small" @click="documentClick(scope.row)" text type="primary"> 附件管理 </el-button>
														<el-button v-if="$hasPer('ChangeAccount4:delete')" @click="deleteHandle(scope.row.n_Id, getData)" class="icon-e" icon="ele-Delete" size="small" text type="danger">
															删除
														</el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="saveId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form label-width="80px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="departmentId" label="部门">
							<el-select v-model="ruleForm.departmentId" placeholder="请选择部门" style="width: 100%">
								<el-option v-for="item in options4" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="changeType" label="变更类型">
							<el-select v-model="ruleForm.changeType" class="m-2" placeholder="请选择变更类型" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="status" label="变更状态">
							<el-select v-model="ruleForm.status" class="m-2" placeholder="请选择变更状态" style="width: 100%" :disabled="!saveId">
								<el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="regionIDsList" label="影响区域">
							<el-select multiple v-model="ruleForm.regionIDsList" class="m-2" placeholder="请选择影响区域" style="width: 100%">
								<el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef, getData)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 查看详情 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDetailDialogVisible" title="详情" width="50%" @close="cancelDetailClick">
			<el-divider content-position="left"> 基本信息 </el-divider>
			<el-descriptions class="margin-top" :column="2" border>
				<el-descriptions-item>
					<template #label> 部门id </template>
					{{ tableData.departmentId }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 部门名称 </template>
					{{ tableData.departmentName }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template #label> 变更类型 </template>
					{{ tableData.changeType }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 变更状态 </template>
					{{ tableData.status }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 影响区域 </template>
					{{ tableData.regionIDs }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 区域名称 </template>
					{{ tableData.regionsName }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 创建时间 </template>
					{{ tableData.createdTime }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 更新时间 </template>
					{{ tableData.updatedTime }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 创建人 </template>
					{{ tableData.createdUserName }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 更新人 </template>
					{{ tableData.updatedUserName }}
				</el-descriptions-item>
			</el-descriptions>
		</el-dialog>
		<!-- 文件上传 -->
		<uploadFile isAccept="" :fileInfo="fileInfo" :isUseDialog="fileDialog" @cancelFileClick="cancelFileClick" @controlFileClick="controlFileClick" @updateData="getData" />
	</div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import { sysOrgList, getChangeLogListApi, addChangeLogApi, deleteChangeLogApi, getChangeLogDetailApi, updateChangeLogApi, getChangeLogAreaApi } from '/@/api/sms/HazardousChemicalsInterface';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import UploadFile from '/@/views/sms/component/reviseUploadFile.vue';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
export default defineComponent({
	name: 'friend-merchant-manage',
	components: {
		SearchModel,
		UploadFile,
	},
	setup() {
		/***** 变量 *****/
		const transferVal = ref(); // 需要查询的值
		const transferVal1 = ref(); // 需要查询的值
		const transferVal2 = ref(); // 需要查询的值
		const showDialogVisible = ref(false);
		let searchObj: any = reactive({});
		// 变更类型
		const options1: any = [
			{ value: 1, label: '设备变更' },
			{ value: 2, label: '工艺变更' },
			{ value: 3, label: '人员变更' },
			{ value: 4, label: '报警变更' },
			{ value: 5, label: '联锁摘除' },
			{ value: 6, label: '联锁投运' },
			{ value: 7, label: '管理变更' },
		];
		// 变更状态
		const options2 = [
			{ value: 1, label: '审核中' },
			{ value: 2, label: '审核通过' },
			{ value: 3, label: '审核不通过' },
		];
		const ruleForm: any = reactive({
			departmentId: '',
			regionIDs: '',
			regionIDsList: '',
			changeType: '', // options1
			status: 2, // options2
		});
		/***** searchClick 查询按钮 *****/
		const searchClick = () => {
			// searchObj.DepartmentId = transferVal.value;
			// searchObj.ChangeType = transferVal1.value;
			// searchObj.Status = transferVal2.value;
			let newObj = Object.keys(searInfo.value);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = searInfo.value[i];
				});
			}
		};

		/***** resetClick 重置按钮 *****/
		const resetClick = () => {
			// transferVal.value = '';
			// transferVal1.value = '';
			// transferVal2.value = '';
			searInfo.value = {};
			let newObj = Object.keys(searchObj);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = '';
					// console.log(i);
				});
			}
			initInfoFun();
		};

		/***** addNodeClick 新增 *****/
		const addNodeClick = async () => {
			showDialogVisible.value = true;
		};

		/***** nodeClick 编辑 *****/
		const options3: any = ref([]);
		const saveId = ref();
		const nodeClick = async (row: any) => {
			console.log(row);
			if (row.n_Id) {
				getChangeLogDetailApi({ Id: row.n_Id }).then((res) => {
					console.log(res);
					ruleForm.departmentId = String(res.data.departmentId);
					const list = res.data.regionIDs.split(',')
					ruleForm.regionIDsList = list.map(i => Number(i))
					ruleForm.changeType = options1.find((i: any) => i.label == res.data.changeType).value;
					ruleForm.status = options2.find((i: any) => i.label == res.data.status).value;

					saveId.value = row.n_Id;
				});
				showDialogVisible.value = true;
			}
		};

		/*** deleteHandle 删除数据事件 */
		const deleteHandle = async (val: String | Number, updateFun: Function) => {
			ElMessageBox.confirm('请确定删除此条数据', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					let param = { id: val };
					try {
						let res: any = await deleteChangeLogApi(param);
						if (res.success) {
							updateFun();
						}
					} catch (err) {
						return;
					}
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '删除失败',
					});
				});
		};

		/*** detailHandle 查看详情事件 */
		const showDetailDialogVisible = ref(false);
		const tableData = ref();
		const detailHandle = async (item: any) => {
			const res = await getChangeLogDetailApi({ Id: item.n_Id });
			console.log(res);
			tableData.value = res.data;
			showDetailDialogVisible.value = true;
		};
		const cancelDetailClick = () => {
			showDialogVisible.value = false;
		};

		/*** cancelUseClick  弹窗取消事件 */
		const cancelUseClick = () => {
			showDialogVisible.value = false;
			saveId.value = 0;
			ruleForm.departmentId = '';
			ruleForm.regionIDs = '';
			ruleForm.regionIDsList = '';
			ruleForm.changeType = ''; // options1
			ruleForm.status = 2; // options2
		};

		/*** controlUseClick  弹窗提交事件 */
		const controlUseClick = async (formEl: FormInstance | undefined, updateFun: Function) => {
			if (!formEl) return;
			await formEl.validate((valid, fields) => {
				if (valid) {
					for (let index = 0; index < ruleForm.regionIDsList.length; index++) {
						if (ruleForm.regionIDsList.at(-1) === index) {
							ruleForm.regionIDs = ruleForm.regionIDsList;
						} else {
							ruleForm.regionIDs = ruleForm.regionIDsList.join(',');
						}
					}
					if (saveId.value) {
						updateChangeLogApi({ ...ruleForm, id: saveId.value });
					} else {
						addChangeLogApi(ruleForm);
					}

					setTimeout(() => {
						cancelUseClick();
						updateFun();
					}, 100);
				} else {
					console.log('error submit!', fields);
				}
			});
		};

		/*** ruleFormRef  表单校验 */
		const ruleFormRef = ref();
		const rules = reactive({
			status: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			changeType: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			regionIDsList: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
			departmentId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
		});

		/*** 附件管理 */
		const fileInfo = ref();
		const fileDialog = ref(false);
		/*** cancelFileClick 文件上传取消事件 */
		const cancelFileClick = () => {
			fileDialog.value = false;
		};

		/*** controlFileClick 文件上传提交事件 */
		const controlFileClick = () => {
			fileDialog.value = false;
		};

		/*** documentClick 文档上传事件 */
		const documentClick = (val: any) => {
			console.log(val, 'val');
			val.sourceType = 10;
			val.sourceId = val.n_Id;
			val.titleCon = '附件上传';
			fileInfo.value = JSON.stringify(val);
			fileDialog.value = true;
		};

		/*** 初始化数据 */
		const basicsInfo: any = ref([]);
		const initInfoFun = () => {
			basicsInfo.value = [
				{
					typeId: 'changeType', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'ChangeType', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '变更类型', // placeholder数据
					defaultProp: options1, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
				{
					typeId: 'status', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'Status', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '变更状态', // placeholder数据
					defaultProp: options2, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
			];
		};

		const searInfo: any = ref();
		const searchHandel = (val: any) => {
			searInfo.value = val;
		};

		const options4: any = ref([]);
		onMounted(async () => {
			const result = await getChangeLogAreaApi();
			result.data.forEach((item: any) => {
				options3.value.push({
					value: item.id,
					label: item.v_Name,
				});
			});

			const res4 = await sysOrgList();
			options4.value = res4.data.map((item: any) => {
				return {
					label: item.name,
					value: item.id,
				};
			});

			await initInfoFun();
		});

		/*** ================================= 导出数据函数操作 ================================= */
		const excelRef: any = ref(null);
		const handleExport = () => {
			if (excelRef.value) {
				if (excelRef.value.data.length !== 0) {
					let tableExcel: any = [];
					let tableArr = excelRef.value.data;
					tableArr.map((item: any) => {
						let tableObj: any = {};
						tableObj['变更类型'] = item.changeType ? item.changeType : '-';
						tableObj['变更状态'] = item.status ? item.status : '-';

						tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
						tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
						tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
						tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
						tableExcel.push(tableObj);
					});
					exportToExcel(tableExcel, '变更台账.xlsx');
				} else {
					ElMessage({
						type: 'error',
						message: '暂无数据导出',
					});
				}
			}
		};

		return {
			...getTableData(getChangeLogListApi, {}, searchObj),
			searchClick,
			transferVal,
			transferVal1,
			transferVal2,
			showDialogVisible,
			deleteHandle,
			ruleForm,
			nodeClick,
			saveId,
			cancelUseClick,
			controlUseClick,
			rules,
			ruleFormRef,
			addNodeClick,
			detailHandle,
			cancelDetailClick,
			showDetailDialogVisible,
			tableData,
			options1,
			options2,
			options4,
			resetClick,
			options3,
			documentClick,
			cancelFileClick,
			controlFileClick,
			fileInfo,
			fileDialog,
			searchHandel,
			basicsInfo,
			handleExport,
			excelRef,
		};
	},
});
</script>

<style lang="scss">
@import '../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
